#include "stdafx.h"

#include <stdio.h>
#include <string.h>
#include "Buffer.h"

#ifdef _WIN32
#ifdef _DEBUG
	#define _CRTDBG_MAP_ALLOC
	#include <stdlib.h>
	#include <crtdbg.h>
	#undef THIS_FILE
	static char THIS_FILE[] = __FILE__;
	#define new       new( _NORMAL_BLOCK, __FILE__, __LINE__)
	#define malloc(s) _malloc_dbg(s, _NORMAL_BLOCK, __FILE__, __LINE__)
#endif
#endif

	
namespace tlnet {

// Constructor
Buffer::Buffer() {
	this->count = 0;
	this->data = NULL;

	this->isReady = false;

	this->prev = this->next = NULL;
}

// Deconstructor
Buffer::~Buffer() {
	if(this->data != NULL) {
		delete[] this->data;
	}
}

// store bytes
bool Buffer::storeBytes(char *data, int count) {
	// if something is currently stored, freed up resources
	if(this->data != NULL) {
		delete[] this->data;
		this->count = 0;
	}

	// size of buffer we are about to allocate
	int buffer_size = count + 1;

	// copy off the buffer (eol is set below)
	this->data = new char[buffer_size];
	strncpy_s(this->data, buffer_size, data, count);
	this->data[count] = '\0';	// adjust eol

	// adjust eol
	this->data[count] = '\0';

	// save the buffer count
	this->count = count;

	// always returns true
	return true;
}

// appened passed in buffer data
bool Buffer::appendBytes(Buffer *buffer) {
	if(this->data == NULL) {
		return storeBytes(buffer->data, buffer->count);
	}

	// save off current buffer
	char *_data = _strdup(this->data);
	int _count = this->count;

	// free up resources
	delete[] this->data;

	// allocate resources for a combined buffer
	this->count += buffer->count;
	this->data = new char[this->count + 1];

	// copy over 1st buffer
	strcpy(this->data, _data);
	// copy over 2nd buffer
	strcpy(this->data + _count, buffer->data);

	// set this buffer to ready, if the merge buffer is
	if(buffer->isReady) {
		this->isReady = true;
	}

	// free up temporary resources
	delete[] _data;

	// always returns true
	return true;
}

}